package com.base.myproject.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.UUID;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.server.busi.BusiInfo;
import com.base.myproject.server.busi.BusiPermissionDB;
import com.base.myproject.server.busi.MenuDB;
import com.base.myproject.server.copy.CopyBusi;
import com.base.myproject.server.database.MakeCode;
import com.base.myproject.server.database.PoolMan;
import com.base.myproject.server.init.MyLogger;
import com.base.myproject.server.ratify.Ratify;
import com.base.myproject.server.ratify.RatifyFlow;
import com.base.myproject.server.tools.OperationADUser;

import datastrux.Pair;

public class BaseServlet extends HttpServlet {
	int requesttime = 0;
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		request.setCharacterEncoding("utf-8");
	
		
		Enumeration  enumeration=request.getParameterNames();
		
		while(enumeration.hasMoreElements())
		{
			String  eeee =""+ enumeration.nextElement();
			System.out.print("e="+eeee+"=");
			System.out.println(request.getParameter(""+eeee));
			
			MyLogger.getInstance().debug(" p="+eeee+" value="+request.getParameter(""+eeee));
			  
		}
		
		
		Date d = new Date();
		java.text.SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		String datestr = sdf.format(d );
		try {
			String action =request.getParameter("Action");
			
			System.err.println("action="+action);
			if(action!=null && action.equals("save"))
			{
				
				
				out.print("save success");
				
				TableSaver tablesave = new TableSaver(request.getParameter("savexml"));
				tablesave.save();
			}
			//小陈加的，用来验证试用期是否到期的。
			else if (action != null && action.equals("validation")) {
				File file = new File("C:\\WINDOWS\\Question.log");//用于保存时间的文件
				DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				boolean success = false;//到期与否
				String writeStartString = "";//第一次访问该软件的日期
				String writeEndString = "";//最后一次访问该软件的日期
				String inputLine = "";
				//第一次访问时用这个分支来创建文件，保存第一次访问和最后一次访问的日期为同一天的值
				if (!file.exists()) {
					file.createNewFile();
					Date today = new Date();
					String str = format.format(today);
					writeStartString = getDateString(str);
					writeEndString = getDateString(str);
					
					writeFile(file, writeStartString, writeEndString);
					success = true;
				} 
				//如果不是第一次访问使用这个分支来读取文件的第一次访问日期和最后一次访问日期
				else {
					BufferedReader br = new BufferedReader(new FileReader(file));
					int lineNumber = 1;
					Date startDate = null;  //保存读出的第一次访问日期
					Date endDate = null;  //保存读出的最后一次访问日期
					while (lineNumber < 3) {  //因为文件只有两行，所以只读两次，第一次为第一次访问的日期，第二次为最后访问的日期
						inputLine = br.readLine();
						if (lineNumber == 1) {
							writeStartString = inputLine;
							startDate = readDate(format, inputLine);
						} else {
							endDate = readDate(format, inputLine);
						}
						lineNumber++;
					}
					
					//最后进行判断，如果没有使用三个月，并且系统时间大于最后使用的日期，就判断为有效，
					//再将新的最后访问日期和原来的第一次访问日期一起写到文件中
					Date today = new Date();
					Calendar c = new GregorianCalendar();
					c.setTime(startDate);
					c.add(Calendar.MONTH, 3);
					startDate = c.getTime();
					if (endDate.before(today)) {
						if (today.before(startDate)) {
							success = true;
							file.delete();
							file.createNewFile();
							String str = format.format(today);
							writeEndString = getDateString(str);
							writeFile(file, writeStartString, writeEndString);
						}
					} else {
						
					}
					
					out.print(success);
				}
			}
			
			/**
			 * 客户登录登录(ccode)
			 */
			else if (action != null && action.equals("ccodelogin")) {
				String name =request.getParameter("name");
				String pass =request.getParameter("pass");
				String str = "";
				if (Login.Ccodelogin(name, pass)) {
					String id = UUID.randomUUID().toString();
					PoolMan pm = new PoolMan();
					String ccode = null;
					try {
						ResultSet rs = pm.executeQuery("select ccode from ccode where loginname ='"+name+"'");
						if(rs.next())
						{
							ccode = rs.getString("ccode");
						}
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					if(ccode == null)
					{
						str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
						str +="<root status='"+Env.LOGINFALSE+"'>";
					
						str +="</root>";
						out.print(str);
						return;
					}
					try {
						UserPool.getInstance().addUser(id, User.CreateUser(name));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.LOGINSUCCESS+"' id='"+id+"' cname='"+name+"' ccode ='"+ccode+"'>";
				
					str +="</root>";
					out.print(str);

				} else {
					str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.LOGINFALSE+"'>";
				
					str +="</root>";
					out.print(str);
				}
			}
			/**
			 * 登录
			 */
			else if (action != null && action.equals("login")) {
				String name =request.getParameter("name");
				String pass =request.getParameter("pass");
				String str = "";
				if (Login.login(name, pass)) {
					String id = UUID.randomUUID().toString();
					PoolMan pm = new PoolMan();
					String bname = null;
					String title = null;
					try {
						ResultSet rs = pm.executeQuery("select a.bname,b.employinnertitle from bcode a, bcode_job b where a.bcode = b.bcode and a.bcode ='"+name+"'");
						if(rs.next())
						{
							bname = rs.getString("bname");
							title = rs.getString("employinnertitle");
						}
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					/*if(bcode == null)
					{
						str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
						str +="<root status='"+Env.LOGINFALSE+"'>";
					
						str +="</root>";
						out.print(str);
						out.flush();
						out.close();
						return;
					}*/
					
					
					try {
						UserPool.getInstance().addUser(id, User.CreateUser(name));
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.LOGINSUCCESS+ "' title ='" + title + "' id='"+id+"' bname='"+bname+"' bcode ='"+name+"'>";
				
					str +="</root>";
					out.print(str);
					out.flush();
					out.close();

				} else {
					str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.LOGINFALSE+"'>";
				
					str +="</root>";
					out.print(str);
					out.flush();
					out.close();
				}
			}
			//登出
			else if (action != null && action.equals("logout")) {
				String system_uuid = request.getParameter("system_uuid");
				String str = "";
				if(system_uuid==null)
				{
					System.err.println("没有登录号！");
				}
				else
				{
					UserPool.getInstance().removeuser(system_uuid);
				str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				str +="<root status='"+Env.LOGOUTSUCCESS+"'>";
			
				str +="</root>";
				UserPool.getInstance().removeuser(system_uuid);
				
				}
				out.print(str);
			}
			//注册
			else if (action != null && action.equals("regiter")) {
				String bname =request.getParameter("bname");
				String pass =request.getParameter("pass");
				String email =request.getParameter("email");
				String dept =request.getParameter("dept");
				String str = "";
				if(Regiter.rigiter(bname, pass, email, dept))
				{
					str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.REGITERSUCCESS+"'>";
				
					str +="</root>";
				}
				else
				{
					str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
					str +="<root status='"+Env.REGITERFALSE+"'>";
				
					str +="</root>";
				}
				
				out.print(str);
			}
			
			
			//用户修改密码
			else if (action != null && action.equals("changepass")) {
				String bcode =request.getParameter("bcode");
				String bname =request.getParameter("bname");
				String oldpass =request.getParameter("oldpass");
				String pass =request.getParameter("pass");
				String Confirmpass =request.getParameter("Confirmpass");
			
				String str = "";
				 PoolMan pm = new PoolMan();
				 String Sql = "update bcode set [password]="+pass+" where bcode="+bcode+" and bname='"+bname+"' and [password]='"+oldpass+"'";
				 
				 try {
					if(pm.Update(Sql)!=0)
					{
						str = ResponseStr(new String[]{"status"},new String[]{Env.SUCCESS});
					}
					else
					{
						str = ResponseStr(new String[]{"status"},new String[]{Env.FALSE});
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("str ="+str);
				out.print(str);
			}
			/**
			 * 插入记录，在basestore中被调用。
			 */
			else if(action!=null && action.equals("needicode"))
			{
				String table = request.getParameter("table");
				String colname = request.getParameter("columnname");
				String colvalue = request.getParameter("columnvalue");
				
				int icode =0;
				 PoolMan pm = new PoolMan();
				  CallableStatement proc = null;
				  proc =  pm.getConnection("test").prepareCall("{call insert_new_row(?,?,?,?)}");
				  proc.setString(1	, table);
				
				 // proc.setInt(2, 1);
		
				  proc.registerOutParameter(2,java.sql.Types.INTEGER);  
				  proc.setInt(2, 1);
				  proc.setString(3	, colname);
				  proc.setString(4	, colvalue);
				  
				  MyLogger.getInstance().debug("needicode="+" table="+table+" colname ="+colname+" colvalue ="+colvalue);
				  
				  proc.executeUpdate();
				  icode = proc.getInt(2);
				  
				
				
				out.print(icode);
				out.flush();
				out.close();
			}
			//测试专用 随时删除
			else if(action!=null && action.equals("test1"))
			{
				System.out.println("000");
				//out.print("zgw");
				out.flush();
				out.close();
			}
			else if(action!=null && action.equals("test"))
			{
				String param = request.getParameter("param");
				String[] value = param.split(","); //用逗号分隔的字符串
				String busicopyid =request.getParameter("busicopyid");
				String busicopyname =request.getParameter("busicopyname");
				StringBuffer sbf = new StringBuffer();
				System.out.println(sbf);
				//type 1 插入  2 当前行修改  默认插入
				String str = "";
	
				
				CopyBusi cb = new CopyBusi(busicopyid,busicopyname,value);
				try {
					str = cb.copyall();
					
					out.println(str);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				
			}
			else if(action!=null && action.equals("loadmenu"))
			{
				String system_uuid = request.getParameter("system_uuid");
				
				if(system_uuid==null)
				{
					System.err.println("没有登录号！");
				}
				
				System.out.println("save in servlet"+system_uuid);
		
				User u = UserPool.getInstance().getUser(system_uuid);
				MenuDB menudb = MenuDB.getInstance();
			
				try {
					String system = request.getParameter("system");
					out.println(menudb.loadMenu(u, system));
					out.flush();
					out.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
				//	MessageBox.alert("错误", "读取菜单的时候出现错误！", null);
					e.printStackTrace();
				}
			}
			/**
			 * 读取数据，客户端直接发送sql，服务器通过查询后返回数据。
			 */
			else if(action!=null && action.equals("getdatasql"))
			{
				String sql = request.getParameter("sql");
				PoolMan pm = new PoolMan();
				try {
					String str = pm.executeQueryXML(sql);
					
					out.print(str);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			/**
			 * 组织表格时用到
			 */
			else if(action!=null && action.equals("Loaddata"))
			{
	
		
				StoreInfo storeinfo = new StoreInfo();
				String sql = request.getParameter("tableinfsql");
				
				if(sql.indexOf("{PERMISSION}")>0)
				{
					//有PERMISSION 必须提交 busicode
					String bcode = request.getParameter("env_bcode");
					String busicode = request.getParameter("busicode");
					String premission = "";
					try {
						premission = BusiPermissionDB.getInstance().getPermissDB(busicode, bcode);
					} catch (Throwable e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
//					Matcher.quoteReplacement("YourString");
				
					sql = sql.replace("{PERMISSION}",premission);
					System.out.println("permission sql ="+sql);
				}
				
				storeinfo.setSql(sql);
				
				storeinfo.setTablename(request.getParameter("tableinftablename"));
				String limit =  request.getParameter("limit");
				//String start = request.getParameter("start");
				String start = request.getParameter("offset");
				
				String advsearch = request.getParameter("advsearch");
				String targetcolumn = request.getParameter("targetcolumn");
				String autoinccolumn = request.getParameter("autoinccolumn");
				String sortcolumn = request.getParameter("sortcolumn");
				String needallrow = request.getParameter("needallrow");
				String forcenolimit = request.getParameter("forcenolimit");
				
				storeinfo.setAdvsearch(advsearch);
				storeinfo.setTargetcolumn(targetcolumn);
				storeinfo.setAutoinccolumn(autoinccolumn);
				storeinfo.setNeedAllRow(needallrow);
				/**
				 * 客户端通知不经心分页
				 */
				if(!forcenolimit.equals("false"))
				{
					limit="0";
				}
				if(sortcolumn!=null)
				{
					storeinfo.setSortcolumn(sortcolumn);
				}
				out.print(jdbc(storeinfo,limit,start));
				Date date2 = new Date();
			//	System.out.println("服务器开始传输数据=="+date2.getTime()/1000);
			}
			//获取打印格式
			else if(action!=null && action.equals("getprinter")) 
			{
//				JSONObject jsonObject = new JSONObject();
//				JSONArray arrayName = new JSONArray();
//				JSONArray arrayValue = new JSONArray();
//				arrayName.set(0, new JSONString("打印1"));
//				arrayName.set(1, new JSONString("打印2"));
//				arrayName.set(2, new JSONString("打印3"));
//				arrayValue.set(0, new JSONString("../js/test/zgw.js"));
//				arrayValue.set(1, new JSONString("../js/test/zgw1.js"));
//				arrayValue.set(2, new JSONString("../js/test/zgw2.js"));
//				jsonObject.put("name", arrayName);
//				jsonObject.put("value", arrayValue);
				String busino = request.getParameter("busino");
				PoolMan pm = new PoolMan();
				//Connection con = null;
				String str = null;

				try {
				String sql = "SELECT printname,jspath FROM printer p where busicode='"+busino+"'";
				ResultSet rs  = pm.executeQuery(sql);
				StringBuffer name=new StringBuffer();
				StringBuffer value=new StringBuffer();
				
					while(rs.next())
					{
						name.append("\""+rs.getString("printname")+"\",");
						value.append("\""+rs.getString("jspath")+"\",");
					}
				if(name.length()>0)
				{
					name= name.deleteCharAt(name.length()-1);
					value= value.deleteCharAt(value.length()-1);
				}
				System.out.println("{\"name\":["+name+"],\"value\":["+value+"]}");
				out.print("{\"name\":["+name+"],\"value\":["+value+"]}");
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				//out.print("{\"name\":[\"打印1\",\"打印3\",\"打印2\"],\"value\":[\"../js/test/zgw.js\",\"../js/test/zgw.js\",\"../js/test/zgw.js\"]}");
				
			}
			//预审批，返回审批链等信息
			else if(action!=null && action.equals("prerityfy"))
			{
				String busicode = request.getParameter("busicode");
				String bcode = request.getParameter("bcode");
				
				RatifyFlow r = RatifyFlow.getInstance();
				r.getRatify(busicode,bcode);
//				System.out.println(r.Strlink.get(0));
//				System.out.println(r.Strlink.get(1));
//				
				if(r.Strlink.size()>0)
				out.println("<table style='width:100%'><tr><td>此任务有"+r.Strlink.size()+"种审批方式。根据具体情况的不同可能有变化。</td></tr><table>");
				
				for(int i=0;i<r.Strlink.size();i++)
				{
					out.println("<table style='width:100%'><tr><td>"+r.Strlink.get(i)+"</tr></table><hr />");
				}
			
			}
		
			else if(action!=null && action.equals("Ratify"))
				
			{
				String busicode = request.getParameter("busicode");
				String bcode = request.getParameter("bcode");
				String busistatus = request.getParameter("busistatus");
				String maintablename = request.getParameter("maintablename");
				String icode = request.getParameter("icode");
				String vprepare = request.getParameter("vprepare");
				BusiInfo bi = new BusiInfo();
				bi.setBcode(bcode );
				bi.setVprepare(vprepare);
				bi.setBusicode(busicode);
				bi.setStatus(busistatus);
				bi.setTablename(maintablename);
				bi.setIcode(icode);
				
			
				String restr = "";
				try {
					restr = Ratify.getInstance(bi, bcode).doRatify("pass","no message");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				out.print(restr);
				out.flush();
				out.close();
			}
			else if(action!=null && action.equals("copyid"))
			{
				out.println("");
			}
			/**
			 * 购物车
			 */
			else if(action!=null && action.equals("addshopcaritem"))
			{
				
			
				String b2cgcode = request.getParameter("b2cgcode");
				String b2cgname = request.getParameter("b2cgname");
				String gcode =  request.getParameter("gcode");
				String gname =  request.getParameter("gname");
				String pric = request.getParameter("pric");
				String discountpric =  request.getParameter("discountpric");
				String ccode = request.getParameter("ccode");
				String imagepath =  request.getParameter("mainimagepath");
				
				PoolMan pm = new PoolMan();
				String sql = "insert  into b2cshopcar (b2cgcode,b2cgname,gcode,gname,shopdate,price,discountprice,ccode,imagepath) values ('"+b2cgcode+"','"+b2cgname+"','"+gcode+"','"+gname+"','"+datestr+"','"+pric+"','"+discountpric+"','"+ccode+"','"+imagepath+"')";
				System.out.println(sql);
				String message = "";
				try {
				 pm.Update(sql);
				} catch (Exception e) {
					System.err.println(sql);
					message="<error>加入购入车时出错！</error>";
					e.printStackTrace();
				}
				out.println(message.equals("")?"<success>ok</success>":message);
			}
			//通过商品的编号将商品加入购物车
			else if(action!=null && action.equals(SystemMessage.getMessage(2, 2)))
			{
				
				String id = request.getParameter("id");
				String message = SystemMessage.getMessage(1, 0);
				String uuid = request.getParameter("system_uuid");
				if(id.indexOf("%")>0)
				{
					message = SystemMessage.getMessage(1, 1)+SystemMessage.getMessage(4, 6);
				}
				else
				{
				PoolMan pm = new PoolMan();
				 message = SystemMessage.getMessage(1, 0);
//				 System.out.println(UserPool.getInstance().getUser(uuid).getName());
//					System.out.println(UserPool.getInstance().getUser(uuid).getBcode());
					
					String ccode =  request.getParameter("system_ccode");
					
				String sql = "insert into b2cshopcar (b2cgcode,b2cgname,gcode,gname,price,discountprice,shopdate,imagepath,ccode) select b2cgcode,b2cgname,gcode,gname,price,discountprice,'"+datestr+"' as adddate,mainimagepath,'"+ccode+"' as ccode from b2cgcode where b2cgcode = '"+id+"'";
				
				
				try {
					pm.Update(sql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					 message = SystemMessage.getMessage(1, 1);
				}
				}
				String str = "";
				str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				str +="<root status='"+message+"'>";
			
				str +="</root>";
				
				//String message="<status>"+SystemMessage.getMessage(1, 0)+"</status>";
				
				out.println(str);
			}
			/*
			 * 删除套装商品
			 */
			else if(action!=null && action.equals(SystemMessage.getMessage(2, 4)))
			{
				String icode = request.getParameter("icode");
				PoolMan pm = new PoolMan();
				String sql = "delete b2csuit where icode ='"+icode+"'";
			
				int updatecount = 0;
				try {
					updatecount= pm.Update(sql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				finally
				{
					try {
						pm.close("test");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			
				if(updatecount ==0)
				{
					out.print(SystemMessage.getMessage(1, 1));
				}
				else
				{
					out.print(SystemMessage.getMessage(1, 0));
				}
				out.flush();
				out.close();
			}
			/**
			 * 添加套装商品
			 */
			else if(action!=null && action.equals(SystemMessage.getMessage(2, 3)))
			{
				
				String str = request.getParameter("b2cgcodestr");
				String b2cgcode = request.getParameter("b2cgcode");
				String suitname = request.getParameter("suitname");
				String[] array = str.split(",");
				PoolMan pm = new PoolMan();
				Vector v = new Vector();
				for(int i=0;i<array.length;i++)
				{
				String sql = " insert into b2csuit (b2cgcode,b2cgcodelink,suitname) values ('"+b2cgcode+"','"+array[i]+"','"+suitname+"')";
				
				v.add(sql);
				}
				
				boolean result = true;
				try {
					pm.getPool("test");
					result = pm.handleTransaction(v);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					
				}
				finally
				{
					try {
						pm.close("test");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(result)
				{
				out.print(SystemMessage.getMessage(1, 0));
		
				}
				else
				{
					out.print(SystemMessage.getMessage(1, 1));
				}
				out.flush();
				out.close();
			}
			//购物车的保存
			else if(action!=null && action.equals(SystemMessage.getMessage(2, 0)))
			{
				
				String sql = request.getParameter("sql");
				
				PoolMan pm = new PoolMan();
				String message = SystemMessage.getMessage(1, 0);
				try {
					pm.Update(sql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					 message = SystemMessage.getMessage(1, 1);
				}
				String str = "";
				str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				str +="<root status='"+message+"'>";
			
				str +="</root>";
				
				//String message="<status>"+SystemMessage.getMessage(1, 0)+"</status>";
				
				out.println(str);
			}
//			购物车的删除
			else if(action!=null && action.equals(SystemMessage.getMessage(2, 1)))
			{
				
				String sql = request.getParameter("sql");
				
				PoolMan pm = new PoolMan();
				String message = SystemMessage.getMessage(1, 0);
				try {
					pm.Update(sql);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					 message = SystemMessage.getMessage(1, 1);
				}
				String str = "";
				str += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				str +="<root status='"+message+"'>";
			
				str +="</root>";
				
				//String message="<status>"+SystemMessage.getMessage(1, 0)+"</status>";
				System.out.println(str);
				out.println(str);
			}
			/**
			 * 获取内码，一般不用，由数据库自动分配
			 */
			else if(action!=null && action.equals("makecode"))
			{
				String table = request.getParameter("table");
				String column = request.getParameter("column");
				int icode = MakeCode.makeCode(table, column);
			}
			/**
			 * 获取外码
			 */
			else if(action!=null && action.equals("makecodename"))
			{
				String table = request.getParameter("table");
				String column = request.getParameter("column");
				String beginstr = request.getParameter("beginstr");
				String codename = MakeCode.makeCode(table, column,beginstr,5);
				out.print(codename);
				out.flush();
				out.close();
			}
/**
 * 获得bcode的组织架构
 */
			else if(action!=null && action.equals("getorganization"))
			{
				String filter = request.getParameter("filter");
				
				StringBuffer sbf = new StringBuffer();
				
				
				sbf.append("<div class=\"hasJS\"><div id=\"contain\">	<ul id=\"sitemap\">");
				
				PoolMan pm = new PoolMan();
				datastrux.Node<Pair> node = null;
				String sql ="select bcode ,bname from bcode where bcode is not null and "+filter+"order by bcode";
				try {
					ResultSet rs = pm.executeQuery(sql);
					
					if(rs.next())
					{
						node=new datastrux.Node<Pair>(new Pair(rs.getString("bcode"),rs.getString("bname")));
					}
					while (rs.next())
					{
//						node=new datastrux.Node(rs.getString("bcode"));
						node.addNodeSort(new datastrux.Node<Pair>(new Pair(rs.getString("bcode"),rs.getString("bname"))));
					}
					
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
//				for(Node n:nodearr)
//				{
//					root.addNodeSort(n);
//				}
//				root.add(new Node("1002"));
//				root.add(new Node("1003"));
//				
			//	node.listNode();
				String str ="<div id=\"contain\"><ul id=\"sitemap\">";
				 str += new String(node.listNode());
				 str +="</ul></div></div>";
				System.out.println(str);
				out.print(str);
				out.flush();
				out.close();
			}
			/**
			 * 获得某商品的剩余库存和显示返回
			 */
			else if(action!=null && action.equals("laststore"))
			{
				
				String cgicode = request.getParameter("cgicode");
				String qty = "0";
				String message = "";
				PoolMan pm = new PoolMan();
				String sql = "select isnull(sum(isnull(a.qty,0)-isnull(b.qty,0)),0) as qty from "; 
				sql+="( ";
				sql+="select qty,cgicode from storeslistg where cgicode ='"+cgicode+"' and inoutflag = 2 "; 
				sql+=") as a ";
				sql+="left join ";
				sql+="( ";
				sql+="select qty,cgicode from storeslistg where cgicode ='"+cgicode+"' and inoutflag = 4 ";
				sql+=") as b ";
				sql+="on a.cgicode = b.cgicode";
				try {
					ResultSet rs = pm.executeQuery(sql);
					if(rs.next())
					{
						qty = rs.getString("qty");
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
					 message ="查询库存出错";
				}
				
				out.print("有的剩余  "+ qty);
				out.flush();
				out.close();
			}
			else if(action!=null && action.equals("download"))
			{
				String type = request.getParameter("type");
				String filter = request.getParameter("filter");
				String bname = request.getParameter("bname");
				String pass = request.getParameter("pass");
				String uuid = UUID.randomUUID().toString();
				DownContainer.getInstance().addLink(uuid,type);
				if(FindUser.isHaveUserbyName_filter_download(bname, pass))
				{
					out.print(ResponseStr(new String[]{"status","linkurl"},new String[]{Env.SUCCESS,uuid}));
				}
				else
				{
					out.print(ResponseStr(new String[]{"status"},new String[]{Env.FALSE}));
				}
				out.flush();
				out.close();
			}
			/**
			 * 获得窗口组织
			 */
			else if(action!=null && action.equals("getdatawin"))
			{
				
			/*	StringBuffer sbf = new StringBuffer();
				sbf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
				sbf.append("<root>");
				sbf.append("<datawin>");
				sbf.append("<columnconfig id='leaguertype' name='家庭成员' width='100'>");
				sbf.append("</columnconfig>");
				sbf.append("<columnconfig id='leaguername' name='姓名' width='100'>");
				sbf.append("</columnconfig>");

				sbf.append("<modeltype name='ccode' map='ccode'>");
				sbf.append("</modeltype>");
				sbf.append("<modeltype name='leaguertype' >");
				sbf.append("</modeltype>");
				
				sbf.append("<storeinfo name = 'ccodelinkman_info' tablename =\"ccodelinkman_info\" sql=\" select * from ccodelinkman_info \">");
				sbf.append("</storeinfo>");
				sbf.append("</datawin>");
				sbf.append("</root>");*/
				
				try {
					String str ="";
					String busicopyname = request.getParameter("busicopyname");
					String busicopyid = request.getParameter("busicopyid");
					String datawinid = request.getParameter("datawinid");
					if(datawinid!=null)
					{
					 str = getDataWin(datawinid);
					}
					else
					{
						 str = getDataWin(busicopyname,busicopyid);
					}
					out.print(str);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else if(action!=null && action.equals("addAd"))
			{
				String name = request.getParameter("name");
				String password = request.getParameter("password");
				
				String addADUserString = "net user " + name + " " + password + " /add";
				operationUser(addADUserString);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		requesttime ++;
		if(requesttime%10==0)
		{
			System.out.println("system gcing "+requesttime);
			System.gc();
			requesttime =0;
			System.out.println("system gced");
		}
		
	}
	
	private void operationUser(String operationUser) {
		OperationADUser operationADUser = new OperationADUser();
		operationADUser.createOperationFile(operationUser);
		String path = operationADUser.getFilePath();
		BufferedReader read = null;
		
		try {
			Process process = Runtime.getRuntime().exec(path);
			read = new BufferedReader(
					new InputStreamReader(process.getInputStream()));
			String str = null;
			while ((str = read.readLine()) != null) {
				System.out.println(str);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			operationADUser.deleteOperationFile();
			try {
				read.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private Date readDate(DateFormat format, String inputLine) {
		Date date = new Date();
		String dateStr = "";
		for (int i=0; i<inputLine.length(); i+=2) {
			dateStr = dateStr + (char)Byte.parseByte(inputLine.substring(i, i+2));
		}
		try {
			date = format.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return date;
	}

	/**
	 * @param file 要写入的文件名
	 * @param writeStartString 写入的第一天访问日期
	 * @param writeEndString 写入的最后访问日期
	 */
	private void writeFile(File file, String writeStartString, String writeEndString) {
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new FileWriter(file));
			bw.write(writeStartString);
			bw.newLine();
			bw.write(writeEndString);
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param 将原来的日期字符串转换为ASCII编码，作为加密后的内容，还有待加强，现在这样还是不安全
	 * @return 加密后的数据
	 */
	private String getDateString(String initString) {
		byte[] bytes = initString.getBytes();
		String returnString = "";
		
		for(int i=0; i<bytes.length; i++) {
			returnString = returnString + + bytes[i];
		}
		return returnString;
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

	/**
	 * Handles the HTTP <code>POST</code> method.
	 * 
	 * @param request
	 *            servlet request
	 * @param response
	 *            servlet response
	 * @throws ServletException
	 *             if a servlet-specific error occurs
	 * @throws IOException
	 *             if an I/O error occurs
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

	static String string2Json(String s) {
		StringBuilder sb = new StringBuilder(s.length() + 20);
		sb.append('\"');
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			default:
				sb.append(c);
			}
		}
		sb.append('\"');
		return sb.toString();
	}

	public String getDataWin(String id) throws Exception
	{
		PoolMan pm = new PoolMan();
		String sql = "select datawin from datawin where id ='"+id+"'";
		ResultSet rs =  pm.executeQuery(sql);
		String str = null;
		while(rs.next())
		{
			str = rs.getString("datawin");
		}
		return str;
	}
	public String getDataWin(String busicopyname,String busicopyid) throws Exception
	{
		PoolMan pm = new PoolMan();
		String sql = "select datawin from datawin where id =(select datawinid from busicopy where busicopyname = '"+busicopyname+"' and busicopyid='"+busicopyid+"')";
		ResultSet rs =  pm.executeQuery(sql);
		String str = null;
		while(rs.next())
		{
			str = rs.getString("datawin");
		}
		return str;
	}
	public String jdbc(StoreInfo storeinfo,String limit,String start) throws SQLException {
		
//		DriverManager.registerDriver(new  com.mysql.jdbc.Driver());
//     	
//   	 Connection connection = DriverManager.getConnection(
//   			"jdbc:mysql://localhost/zz?useUnicode=true&characterEncoding=GBK","root","123321");
//    java.sql.Statement   stmt =  connection.createStatement();
//     ResultSet  result = stmt.executeQuery("SELECT * FROM gcode");
//     result.next();
//     System.out.println(result.getString("gcode"));

		PoolMan pm = new PoolMan();
		//Connection con = null;
		String str = null;

		try {
		//	con = pm.getPool("test");
		//	System.out.println(storeinfo.getSql());
			String sql = storeinfo.getSql();
			System.out.println(sql);
			String advfilter = "";
			
			if(storeinfo.getNeedAllRow()!=null)
			{
				return pm.executeQueryXMLNeedAllRow(sql);
			}
			
			
			if(storeinfo.getAdvsearch()!=null)
			{
				String[] filterarr = storeinfo.getTargetcolumn().split(",");
				for(int i=0;i<filterarr.length;i++)
				{
					advfilter +=filterarr[i]+" like '%"+storeinfo.getAdvsearch()+"%' or  ";
				}
				advfilter = advfilter.substring(0, advfilter.length()-5); //去掉尾巴的  and
		
			if(advfilter.length()>0)
			{
				if(sql.indexOf("where")>0)
				{
				sql = sql.substring(0, sql.indexOf("where")+5)+" (" +advfilter+")"+sql.substring(sql.indexOf("where"));
				}
				else
				{
					sql = sql + " where "+advfilter;
				}
			}
			}
			if(storeinfo.getSortcolumn()!=null)
			{
				sql = sql +" order by " +storeinfo.getSortcolumn();
			}
		//	System.out.println(storeinfo.getSql());
			if(!(storeinfo.getAutoinccolumn()==null || storeinfo.getAutoinccolumn().equals("")))
			{
				//TODO bcode yao xiugai
			String bcode = "zgw";
			//获得自增字段的sql	select substring(ccode,CHARINDEX('_',ccode)+1,len(ccode)) from ccodeofficeaddress where ccode like 'zz_%'
			String autoincsql = "select isnull(max(substring("+storeinfo.getAutoinccolumn()+",CHARINDEX('_',"+storeinfo.getAutoinccolumn()+")+1,len("+storeinfo.getAutoinccolumn()+"))),0) as inc from "+storeinfo.getTablename()+" where "+storeinfo.getAutoinccolumn()+" like '"+bcode+"_%'";
			str = pm
					.executeQueryXML(sql,autoincsql,limit,start);
	
			}
			else
			{
				str = pm
				.executeQueryXML(sql,null,limit,start);
			}
//			while(rs1.next())
//			{
//				System.out.println(rs1.getString("gcode"));
//			}
		
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		finally
		{
			try {
				pm.close("test");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//System.out.println(str);
		return str;
	}
/**
 * response 的组织，到客户端可以获得xml
 * 参数  status
 * @param keys
 * @param messages
 * @return
 */
	static String ResponseStr(String[] keys,String[] messages )
	{
		String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
				str +="<root ";
			
				for(int i=0;i<keys.length && i<messages.length;i++)
				{
					str+=keys[i]+"='"+messages[i]+"' ";
				}
				str +="></root>";
				
				System.out.println("str ="+str);
				return str;
	}
}
